import React, { useState } from 'react'
import {
  Space,
  Button,
  Dropdown,
  Modal,
  Form,
  Input,
  Select,
  Upload,
  message,
  Tooltip,
  Badge,
  Typography,
} from 'antd'
import {
  PlusOutlined,
  ImportOutlined,
  ExportOutlined,
  DeleteOutlined,
  CopyOutlined,
  FolderAddOutlined,
  MoreOutlined,
  UploadOutlined,
  DownloadOutlined,
  SyncOutlined,
  SettingOutlined,
} from '@ant-design/icons'
import { useAppSelector, useAppDispatch } from '@/store'
import { createScript } from '@/store/slices/scriptSlice'
import { addNotification } from '@/store/slices/uiSlice'
import * as scriptAPI from '@/services/scriptAPI'
import * as folderAPI from '@/services/folderAPI'
import { downloadFile } from '@/utils'

const { TextArea } = Input
const { Option } = Select
const { Text } = Typography

interface ScriptToolbarProps {
  selectedScripts?: string[]
  currentFolderId?: string | null
  onRefresh?: () => void
  onScriptCreated?: () => void
  onBulkOperation?: (operation: string, scriptIds: string[]) => void
}

const ScriptToolbar: React.FC<ScriptToolbarProps> = ({
  selectedScripts = [],
  currentFolderId,
  onRefresh,
  onScriptCreated,
  onBulkOperation,
}) => {
  const dispatch = useAppDispatch()
  const { theme } = useAppSelector(state => state.ui)
  
  // 模态框状态
  const [createModalVisible, setCreateModalVisible] = useState(false)
  const [importModalVisible, setImportModalVisible] = useState(false)
  const [exportModalVisible, setExportModalVisible] = useState(false)
  const [createFolderModalVisible, setCreateFolderModalVisible] = useState(false)
  
  const [form] = Form.useForm()
  const [folderForm] = Form.useForm()
  
  // 文件上传状态
  const [uploading, setUploading] = useState(false)
  const [fileList, setFileList] = useState<any[]>([])

  // 创建新脚本
  const handleCreateScript = async () => {
    try {
      const values = await form.validateFields()
      
      await dispatch(createScript({
        name: values.name,
        description: values.description,
        content: values.content || '-- 新建脚本\nSELECT 1;',
        tags: values.tags || [],
        folder_id: currentFolderId,
        created_by: '当前用户',
      }))
      
      message.success('脚本创建成功')
      setCreateModalVisible(false)
      form.resetFields()
      onScriptCreated?.()
    } catch (error) {
      message.error('创建脚本失败')
    }
  }

  // 创建文件夹
  const handleCreateFolder = async () => {
    try {
      const values = await folderForm.validateFields()
      
      await folderAPI.createFolder({
        name: values.name,
        parent_id: currentFolderId,
        created_by: '当前用户',
      })
      
      message.success('文件夹创建成功')
      setCreateFolderModalVisible(false)
      folderForm.resetFields()
      onRefresh?.()
    } catch (error) {
      message.error('创建文件夹失败')
    }
  }

  // 导入脚本
  const handleImportScripts = async () => {
    if (fileList.length === 0) {
      message.warning('请选择要导入的文件')
      return
    }

    try {
      setUploading(true)
      
      const files = fileList.map(file => file.originFileObj)
      const formData = new FormData()
      files.forEach(file => formData.append('files', file))
      
      if (currentFolderId) {
        formData.append('folder_id', currentFolderId)
      }
      formData.append('created_by', '当前用户')
      
      const response = await scriptAPI.importScripts(files as any, {
        folder_id: currentFolderId,
        created_by: '当前用户',
      })
      
      message.success(`导入完成：成功 ${response.data.success_count} 个，失败 ${response.data.failed_count} 个`)
      
      if (response.data.errors.length > 0) {
        Modal.info({
          title: '导入详情',
          content: (
            <div>
              <p>导入过程中遇到以下问题：</p>
              <ul>
                {response.data.errors.map((error, index) => (
                  <li key={index}>{error}</li>
                ))}
              </ul>
            </div>
          ),
        })
      }
      
      setImportModalVisible(false)
      setFileList([])
      onRefresh?.()
    } catch (error) {
      message.error('导入脚本失败')
    } finally {
      setUploading(false)
    }
  }

  // 导出脚本
  const handleExportScripts = async (scriptIds: string[], format: string = 'zip') => {
    try {
      const blob = await scriptAPI.exportScripts(scriptIds, format)
      downloadFile(blob, `scripts_export_${Date.now()}.${format}`)
      message.success('脚本导出成功')
    } catch (error) {
      message.error('导出脚本失败')
    }
  }

  // 批量删除
  const handleBulkDelete = () => {
    if (selectedScripts.length === 0) {
      message.warning('请先选择要删除的脚本')
      return
    }

    Modal.confirm({
      title: '批量删除确认',
      content: `确定要删除选中的 ${selectedScripts.length} 个脚本吗？此操作不可恢复。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        onBulkOperation?.('delete', selectedScripts)
      },
    })
  }

  // 批量复制
  const handleBulkCopy = () => {
    if (selectedScripts.length === 0) {
      message.warning('请先选择要复制的脚本')
      return
    }
    onBulkOperation?.('copy', selectedScripts)
  }

  // 批量移动
  const handleBulkMove = () => {
    if (selectedScripts.length === 0) {
      message.warning('请先选择要移动的脚本')
      return
    }
    // 这里可以打开文件夹选择对话框
    message.info('批量移动功能开发中')
  }

  // 获取批量操作菜单
  const getBulkOperationMenu = () => ({
    items: [
      {
        key: 'copy',
        icon: <CopyOutlined />,
        label: `复制 ${selectedScripts.length} 个脚本`,
        onClick: handleBulkCopy,
      },
      {
        key: 'move',
        icon: <FolderAddOutlined />,
        label: `移动 ${selectedScripts.length} 个脚本`,
        onClick: handleBulkMove,
      },
      {
        key: 'export',
        icon: <ExportOutlined />,
        label: `导出 ${selectedScripts.length} 个脚本`,
        onClick: () => setExportModalVisible(true),
      },
      { type: 'divider' as const },
      {
        key: 'delete',
        icon: <DeleteOutlined />,
        label: `删除 ${selectedScripts.length} 个脚本`,
        danger: true,
        onClick: handleBulkDelete,
      },
    ],
  })

  // 获取更多操作菜单
  const getMoreActionsMenu = () => ({
    items: [
      {
        key: 'refresh',
        icon: <SyncOutlined />,
        label: '刷新列表',
        onClick: onRefresh,
      },
      {
        key: 'import',
        icon: <ImportOutlined />,
        label: '导入脚本',
        onClick: () => setImportModalVisible(true),
      },
      {
        key: 'export-all',
        icon: <ExportOutlined />,
        label: '导出所有脚本',
        onClick: () => setExportModalVisible(true),
      },
      { type: 'divider' as const },
      {
        key: 'create-folder',
        icon: <FolderAddOutlined />,
        label: '新建文件夹',
        onClick: () => setCreateFolderModalVisible(true),
      },
    ],
  })

  return (
    <div style={{ 
      padding: '12px 16px', 
      borderBottom: '1px solid #f0f0f0',
      background: theme === 'dark' ? '#1f1f1f' : '#fafafa',
    }}>
      <Space size="middle">
        {/* 主要操作按钮 */}
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setCreateModalVisible(true)}
        >
          新建脚本
        </Button>

        {/* 批量操作按钮 */}
        {selectedScripts.length > 0 && (
          <Dropdown menu={getBulkOperationMenu()} trigger={['click']}>
            <Button>
              批量操作
              <Badge count={selectedScripts.length} size="small" />
            </Button>
          </Dropdown>
        )}

        {/* 更多操作 */}
        <Dropdown menu={getMoreActionsMenu()} trigger={['click']}>
          <Button icon={<MoreOutlined />}>
            更多操作
          </Button>
        </Dropdown>

        {/* 右侧操作 */}
        <div style={{ marginLeft: 'auto' }}>
          <Space>
            <Tooltip title="刷新列表">
              <Button
                icon={<SyncOutlined />}
                onClick={onRefresh}
              />
            </Tooltip>
          </Space>
        </div>
      </Space>

      {/* 新建脚本模态框 */}
      <Modal
        title="新建脚本"
        open={createModalVisible}
        onOk={handleCreateScript}
        onCancel={() => {
          setCreateModalVisible(false)
          form.resetFields()
        }}
        okText="创建"
        cancelText="取消"
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="脚本名称"
            rules={[
              { required: true, message: '请输入脚本名称' },
              { max: 100, message: '脚本名称不能超过100个字符' },
            ]}
          >
            <Input placeholder="输入脚本名称" autoFocus />
          </Form.Item>
          
          <Form.Item
            name="description"
            label="脚本描述"
          >
            <TextArea 
              rows={3} 
              placeholder="输入脚本描述（可选）" 
              maxLength={500}
              showCount
            />
          </Form.Item>
          
          <Form.Item
            name="tags"
            label="标签"
          >
            <Select
              mode="tags"
              placeholder="输入标签，按回车添加"
              style={{ width: '100%' }}
              tokenSeparators={[',', ' ']}
            />
          </Form.Item>
          
          <Form.Item
            name="content"
            label="初始内容"
          >
            <TextArea 
              rows={6} 
              placeholder="输入初始SQL内容（可选）"
              style={{ fontFamily: 'Monaco, Consolas, monospace' }}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 新建文件夹模态框 */}
      <Modal
        title="新建文件夹"
        open={createFolderModalVisible}
        onOk={handleCreateFolder}
        onCancel={() => {
          setCreateFolderModalVisible(false)
          folderForm.resetFields()
        }}
        okText="创建"
        cancelText="取消"
      >
        <Form form={folderForm} layout="vertical">
          <Form.Item
            name="name"
            label="文件夹名称"
            rules={[
              { required: true, message: '请输入文件夹名称' },
              { max: 50, message: '文件夹名称不能超过50个字符' },
            ]}
          >
            <Input placeholder="输入文件夹名称" autoFocus />
          </Form.Item>
          
          {currentFolderId && (
            <div style={{ color: '#666', fontSize: 12 }}>
              将在当前文件夹下创建子文件夹
            </div>
          )}
        </Form>
      </Modal>

      {/* 导入脚本模态框 */}
      <Modal
        title="导入脚本"
        open={importModalVisible}
        onOk={handleImportScripts}
        onCancel={() => {
          setImportModalVisible(false)
          setFileList([])
        }}
        okText="导入"
        cancelText="取消"
        confirmLoading={uploading}
        width={600}
      >
        <div style={{ marginBottom: 16 }}>
          <Text type="secondary">
            支持导入 .sql 文件，可以选择多个文件批量导入。
          </Text>
        </div>
        
        <Upload
          multiple
          accept=".sql"
          fileList={fileList}
          onChange={({ fileList }) => setFileList(fileList)}
          beforeUpload={() => false} // 阻止自动上传
          onRemove={(file) => {
            setFileList(fileList.filter(f => f.uid !== file.uid))
          }}
        >
          <Button icon={<UploadOutlined />}>选择文件</Button>
        </Upload>
        
        {fileList.length > 0 && (
          <div style={{ marginTop: 16 }}>
            <Text type="secondary">
              已选择 {fileList.length} 个文件
            </Text>
          </div>
        )}
      </Modal>

      {/* 导出脚本模态框 */}
      <Modal
        title="导出脚本"
        open={exportModalVisible}
        onCancel={() => setExportModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setExportModalVisible(false)}>
            取消
          </Button>,
          <Button 
            key="export-zip" 
            type="primary"
            onClick={() => {
              const scriptIds = selectedScripts.length > 0 ? selectedScripts : []
              handleExportScripts(scriptIds, 'zip')
              setExportModalVisible(false)
            }}
          >
            导出为ZIP
          </Button>,
        ]}
      >
        <div>
          <p>选择导出格式：</p>
          <Space direction="vertical" style={{ width: '100%' }}>
            <Button 
              block 
              icon={<DownloadOutlined />}
              onClick={() => {
                const scriptIds = selectedScripts.length > 0 ? selectedScripts : []
                handleExportScripts(scriptIds, 'zip')
                setExportModalVisible(false)
              }}
            >
              ZIP压缩包 (.zip)
            </Button>
            <Button 
              block 
              icon={<DownloadOutlined />}
              onClick={() => {
                const scriptIds = selectedScripts.length > 0 ? selectedScripts : []
                handleExportScripts(scriptIds, 'sql')
                setExportModalVisible(false)
              }}
            >
              单个SQL文件 (.sql)
            </Button>
          </Space>
          
          {selectedScripts.length > 0 ? (
            <div style={{ marginTop: 16, color: '#666', fontSize: 12 }}>
              将导出选中的 {selectedScripts.length} 个脚本
            </div>
          ) : (
            <div style={{ marginTop: 16, color: '#666', fontSize: 12 }}>
              将导出当前文件夹下的所有脚本
            </div>
          )}
        </div>
      </Modal>
    </div>
  )
}

export default ScriptToolbar